# 2021-8-27 from gitee.zth 更新 by grx
from rest_framework.decorators import api_view
from questionnaire.models import *
from operator import itemgetter
from rest_framework.response import Response
from rest_framework import status
import datetime
import pytz
from django.db.models import Q
from django.db.models import Count

# 填写问卷总份数统计
def reclaimingQuantity(qid):
    res = Submit.objects.filter(wjId=qid).filter(is_submitted=True).aggregate(c=Count("id"))
    return res['c']


def alQuestionnaire(username, reverse, sorted_by):
    if reverse or sorted_by != "publish_time":
        questionnaire = Questionnaire.objects.filter(username=username, is_deleted=False).order_by("-publish_time")
    else:
        questionnaire = Questionnaire.objects.filter(username=username, is_deleted=False).order_by("publish_time")
    response = {'questionnaires': {}}
    alq = []
    for item in questionnaire:
        temp = {
            'id': item.id,
            'name': item.title,
            'publish_time': item.publish_time,
            'created_time': item.created_time,
            'quantity': reclaimingQuantity(item.id),
            'type': item.type,
            'status':item.status
        }
        alq.append(temp)
    response['alq'] = alq
    # response['alq'].sort(key=itemgetter('quantity'))
    return response


def alSearchQuestionnire(username, title, sorted_by, reverse):
    if reverse or sorted_by != "publish_time":
        questionnaire = Questionnaire.objects.filter(Q(title__icontains=title), username=username,
                                                     is_deleted=False).order_by("-publish_time")
    else:
        questionnaire = Questionnaire.objects.filter(Q(title__icontains=title), username=username,
                                                     is_deleted=False).order_by("publish_time")
    response = {'questionnaires': {}}
    alq = []
    for item in questionnaire:
        temp = {
            'id': item.id,
            'name': item.title,
            'publish_time': item.publish_time,
            'created_time': item.created_time,
            'quantity': reclaimingQuantity(item.id),
            'type': item.type,
            'status': item.status
        }
        alq.append(temp)
    response['alq'] = alq
    return response

@api_view(['POST', ])
def questionnaireSort(request):
    username = request.data.get('username')
    page = request.data.get('page')
    page = int(page)
    reverse = request.data.get('reverse')        #可以选择正序倒序  reverse = True倒序，reverse = False正序
    sorted_by = request.data.get('sorted_by')    #可以根据publish_time、quantity、created_time排序
    al_q = alQuestionnaire(username,reverse, sorted_by)
    if sorted_by == "created_time":
        al_q['alq'].sort(key=itemgetter('created_time'), reverse=reverse)
    elif sorted_by == "quantity":
        al_q['alq'].sort(key=itemgetter('quantity'), reverse=reverse)
    length = len(al_q['alq'])
    if length % 10 == 0:
        total_page = length // 10
    else:
        total_page = length // 10 + 1
    response = {'code': 0, 'msg': '操作成功', 'questionnaires': {}}
    questionnare = []
    if page <= total_page and length != 0:
        if page == total_page:
            for i in range((page - 1) * 10, length):
                questionnare.append(al_q['alq'][i])
        else:
            for i in range((page - 1) * 10, page * 10):
                questionnare.append(al_q['alq'][i])
    response['questionnaires'] = questionnare
    response['total_page'] = total_page
    return Response(response, status=status.HTTP_200_OK)


@api_view(['POST', ])
def searchQuestionnaire(request):
    username = request.data.get('username')
    page = request.data.get('page')
    page = int(page)
    title = request.data.get('title')
    sorted_by = request.data.get('sorted_by')
    reverse = request.data.get('reverse')
    al_q = alSearchQuestionnire(username, title, sorted_by, reverse)
    if sorted_by != "publish_time":
        al_q['alq'].sort(key=itemgetter(sorted_by), reverse = reverse)
    length = len(al_q['alq'])
    if length % 10 == 0:
        total_page = length // 10
    else:
        total_page = length // 10 + 1
    response = {'code': 0, 'msg': '操作成功', 'questionnaires': {}}
    questionnare = []
    if page <= total_page and length != 0:
        if page == total_page:
            for i in range((page - 1) * 10, length):
                questionnare.append(al_q['alq'][i])
        else:
            for i in range((page - 1) * 10, page * 10):
                questionnare.append(al_q['alq'][i])
    response['questionnaires'] = questionnare
    response['total_page'] = total_page
    return Response(response, status=status.HTTP_200_OK)


@api_view(['POST', ])
def copyQuestionnaire(request):
    print(request.data)
    wid = request.data.get('qid')
    # 找到需要复制的问卷的信息和问卷中题目的信息
    questionnaire = Questionnaire.objects.filter(id=wid).first()
    # 复制问卷信息
    questionnaire_cpy = Questionnaire.objects.create(
        title=questionnaire.title + '的副本',
        username=questionnaire.username,
        status=0,  # 副本是未发布状态
        desc=questionnaire.desc,
        publish_time=None,
        start_time=None,
        end_time=None,
        is_remind=questionnaire.is_remind,
        is_allowed_to_change=False,
        is_out_of_order=False,
        is_set_date=False,
        is_deleted=questionnaire.is_deleted,
        show_number=False,
        type=questionnaire.type,
        limit=questionnaire.limit
    )
    questions = Question.objects.filter(wjId=wid)
    if Question.objects.filter(wjId=wid).count() == 0:
        return Response({'msg': '创建成功', 'code': 0}, status=status.HTTP_200_OK)
    # 循环复制问题信息
    for q in questions:
        question_object = Question.objects.create(
            title=q.title,
            type=q.type,
            wjId=questionnaire_cpy.id,
            row=q.row,
            must=q.must,
            remark=q.remark,
            score=q.score,
            correct_option=q.correct_option,
            correct_answer=q.correct_answer
        )
        options = Options.objects.filter(questionId=q.id)
        for option in options:
            Options.objects.create(questionId=question_object.id, title=option.title, limit=option.limit, remain=option.limit, is_correct=option.is_correct)
        if q.type == 'grade':
            g = GradeQuestionAttribute.objects.get(questionId=q.id)
            GradeQuestionAttribute.objects.create(questionId=question_object.id,
                                                  grade_type=g.grade_type,
                                                  degree_max=g.degree_max,
                                                  degree_min=g.degree_min,
                                                  range=g.range,
                                                  start=g.start)

    response = {'code': 0, 'msg': '操作成功'}
    return Response(response, status=status.HTTP_200_OK)


@api_view(['POST', ])
def deleteQuestionnaire(request):
    qid = request.data.get('qid')
    is_deleted = request.data.get('is_delete')
    questionnaire = Questionnaire.objects.get(id=qid)
    # 将是否被回收设为是，即标记为已被删除
    questionnaire.is_deleted = is_deleted
    questionnaire.save()
    response = {
        'code': 0,
        'msg': '操作成功'
    }
    return Response(response, status=status.HTTP_200_OK)


# 修改问卷的开启关闭状态
@api_view(['POST', ])
def changeStatus(request):
    qid = request.data.get('questionnaire_id')
    # status = request.data.get('status')
    questionnaire = Questionnaire.objects.get(id=qid)
    if questionnaire.status == 0:
        questionnaire.status = 1  # 状态1为已发布
        if questionnaire.publish_time is None:
            questionnaire.publish_time = datetime.datetime.now().replace(tzinfo=pytz.timezone('UTC'))
    elif questionnaire.status == 1:
        questionnaire.status = 0  # 状态0为关闭
        questionnaire.publish_time = None
    questionnaire.save()
    response = {
        'code': 0,
        'msg': '操作成功'
    }
    return Response(response, status=status.HTTP_200_OK)


def alDeleteList(username):
    questionnaire = Questionnaire.objects.filter(username=username, is_deleted=True)
    response = {'questionnaires': {}}
    alq = []
    for item in questionnaire:
        temp = {}
        temp['id'] = item.id
        temp['name'] = item.title
        temp['type'] = item.type
        alq.append(temp)
    response['alq'] = alq
    return response


@api_view(['POST', ])
def deleteList(request):
    username = request.data.get('username')
    page = request.data.get('page')
    page = int(page)
    al_q = alDeleteList(username)
    length = len(al_q['alq'])
    if length % 10 == 0:
        total_page = length//10
    else:
        total_page = length//10 + 1
    response = {'code': 0, 'msg': '操作成功', 'questionnaires':{}}
    questionnare = []
    if page <= total_page and length != 0:
        if page == total_page:
            for i in range((page - 1) * 10, length):
                questionnare.append(al_q['alq'][i])
        else:
            for i in range((page - 1) * 10, page * 10):
                questionnare.append(al_q['alq'][i])
    response['questionnaires'] = questionnare
    response['total_page'] = total_page
    return Response(response, status=status.HTTP_200_OK)